package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"srv/models/mysqlinit"
	"srv/pkg"
	"strconv"

	"srv/internal/svc"
	"srv/srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *srv.CreateOrderRequest) (*srv.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line
	h := mysqlinit.House{}
	err := h.FindHouse(in.HouseId)
	if err != nil {
		logx.Error("获取房源详情失败")
		return nil, errors.New("获取房源详情失败")
	}
	if h.ID == 0 {
		logx.Error("房源不存在")
		return nil, errors.New("房源不存在")
	}

	o := mysqlinit.Order{}
	OrderSn := uuid.NewString()
	Amount := h.HousePrice * float64(in.Num)
	o = mysqlinit.Order{

		HouseId: int(in.HouseId),
		OrderSn: OrderSn,
		Amount:  Amount,
	}
	err = o.CreateOrder()
	if err != nil {
		logx.Error("订单创建失败")
		return nil, errors.New("订单创建失败")
	}
	totalAmount := strconv.FormatFloat(Amount, 'f', 2, 64)

	url := pkg.Pay(o.OrderSn, totalAmount)
	return &srv.CreateOrderResponse{
		Url: url,
	}, nil
}
